import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { decodeAES, encodeAES } from '@/utils/aesRsa'
import { setting } from '@/utils/axios/setting'
import type { TokenType } from '@/api/auth/types'
const { wsLocal } = useCache()

export type LoginFormType = {
  tenantName: string
  username: string
  password: string
  rememberMe: boolean
}
// 获取token
export const getAccessToken = () => {
  return wsLocal.getItem(CACHE_KEY.SYSTEM_ACCESS_TOKEN)
}
// 获取刷新token
export const getRefreshToken = () => {
  return wsLocal.getItem(CACHE_KEY.SYSTEM_REFRESH_TOKEN)
}
// 设置token
export const setToken = (token: TokenType) => {
  if (setting.is_refresh_token_enable) {
    wsLocal.setItem(CACHE_KEY.SYSTEM_REFRESH_TOKEN, token.refreshToken)
  }
  wsLocal.setItem(CACHE_KEY.SYSTEM_ACCESS_TOKEN, token.accessToken)
}
// 删除token
export const removeToken = () => {
  if (setting.is_refresh_token_enable) {
    wsLocal.removeItem(CACHE_KEY.SYSTEM_REFRESH_TOKEN)
  }
  wsLocal.removeItem(CACHE_KEY.SYSTEM_ACCESS_TOKEN)
}
// token 格式化
export const formatToken = (token: string) => {
  return 'Bearer ' + token
}
// =========== 账号相关 ==========
// 获取登录表单数据缓存
export const getLoginFormCache = () => {
  if (wsLocal.getItem(CACHE_KEY.LOGIN_FORM)) {
    return decodeAES(wsLocal.getItem(CACHE_KEY.LOGIN_FORM))
  } else {
    return false
  }
}
// 设置登录表单数据缓存
export const setLoginFormCache = value => {
  wsLocal.setItem(CACHE_KEY.LOGIN_FORM, encodeAES(value))
}
// 移除登录表单数据缓存
export const removeLoginFormCache = () => {
  wsLocal.removeItem(CACHE_KEY.LOGIN_FORM)
}
// =========== 租户相关 ==========
// 获取租户ID缓存
export const getTenantIdCache = () => {
  if (wsLocal.getItem(CACHE_KEY.LOGIN_TENANT_ID)) {
    return decodeAES(wsLocal.getItem(CACHE_KEY.LOGIN_TENANT_ID))
  } else {
    return false
  }
}
// 设置租户ID缓存
export const setTenantIdCache = value => {
  wsLocal.setItem(CACHE_KEY.LOGIN_TENANT_ID, encodeAES(value))
}
// 移除租户ID缓存
export const removeTenantIdCache = () => {
  wsLocal.removeItem(CACHE_KEY.LOGIN_TENANT_ID)
}
